import User from "../models/user.model.js"
import jwt from "jsonwebtoken"

// if protectRoute() runs ok, then goto next()
export const protectRoute = async (req, res, next) => {
    try {
        const token = req.cookie.jwt

        if (!token) {
            return res.status(401).json({
                error: "Unauthorized: No jwt token provided"
            })
        }

        const decoded = jwt.verify(token, process.env.JWT_SECRET)
        if (!decoded) {
            return res.status(401).json({
                error: "Unauthorized: Invalid jwt token"
            })
        }

        const user = await User.findById(decoded.userId).select("-password")
        if (!user) {
            return res.status(404).json({
                error: "User not found"
            })
        }

        req.user = user
        next()
    } catch (error) {
        console.log("Error in protectRoute middleware ", error.message)
        return res.status(500).json({
            error: "Internal Server Error"
        })
    }
}
